package com.sgb.kjwl.view.ui.activity.transport;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityOfflineCollectionConfirmBinding;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.transport.driver.trans.TransportFreightCollectionActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.viewmodel.transport.OfflineCollectionConfirmModel;
import com.swgk.core.dialog.DialogHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * Describe:    线下收款确认
 * Author:  yangLei
 * Date:    2021/7/6
 */
public class OfflineCollectionConfirmActivity extends AppActivity {

    private ActivityOfflineCollectionConfirmBinding binding;
    private OfflineCollectionConfirmModel viewModel;

    //图片上传
    private List<LocalMedia> selectList = new ArrayList<>();
    private ImageAdapter adapter;
    private List<String> urls = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();
    private int currentImgIndex;
    private String urlStrings = "";
    private String orderNo = "";
    private String freight = "";

    public static void start(Context context, String orderNo, String freight) {
        Intent intent = new Intent();
        intent.setClass(context, OfflineCollectionConfirmActivity.class);
        intent.putExtra("freight", freight);
        intent.putExtra("orderNo", orderNo);
        context.startActivity(intent);
    }

    public static void startForResult(Activity activity, String orderNo, String freight, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(activity, OfflineCollectionConfirmActivity.class);
        intent.putExtra("freight", freight);
        intent.putExtra("orderNo", orderNo);
        activity.startActivityForResult(intent, requestCode);

    }

    @Override
    protected void initView() {
        orderNo = getIntent().getStringExtra("orderNo");
        freight = getIntent().getStringExtra("freight");

        viewModel = new ViewModelProvider(this).get(OfflineCollectionConfirmModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_offline_collection_confirm);
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.sureStart.setOnClickListener(this);
        binding.topLayout.titleView.setText("线下收款确认");
        if (!TextUtils.isEmpty(freight)) {
            binding.freight.setText(NumberUtil.trim0(freight) + "元");
        } else {
            binding.freight.setText("0元");
        }
        adapter = new ImageAdapter(this, null, null, 3);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(OfflineCollectionConfirmActivity.this, 4));
        binding.recyclerView.setAdapter(adapter);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.sureStart.setOnClickListener(this);

        viewModel.uploadImgLD.observe(this, s -> uploadImgSuccess(s));
        viewModel.sureCollectionLD.observe(this, s -> {
            setResult(TransportFreightCollectionActivity.OFFLINE_RESULT_CODE);
            ZMessageEvent event = new ZMessageEvent();
            event.code = Constants.EVENT_PAY_SUCCESS;
            EventBus.getDefault().post(event);
            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                    Pair.create("isGoodsOwner", 0));

            finish();
        });
    }


    public void uploadImgSuccess(String url) {
        dealUrlString(url);
        uploadImgAndSureCollection();
    }

    private void dealUrlString(String url) {
        if (TextUtils.isEmpty(urlStrings)) {
            urlStrings = url;
        } else {
            urlStrings = urlStrings + "," + url;
        }
    }

    /**
     * 上传图片并确认收款
     */
    private void uploadImgAndSureCollection() {
        if (currentImgIndex < fileList.size()) {
            viewModel.uploadMultiFileModel(this, adapter.getFileList().get(currentImgIndex++));
        } else {
            //图片上传完成后的操作
            viewModel.sureCollection(orderNo, urlStrings);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.sure_start:
                onCollectionConfirm();
                break;
        }
    }

    /**
     * 确认收款
     */
    private void onCollectionConfirm() {
        DialogHelper.showProgressDialog(this, "文件上传中...").setCancelable(false);
        boolean unSelectedFile = fileList.size() == 0 || adapter.getFileList() == null
                || adapter.getFileList().size() == 0;
        if (unSelectedFile) {
            viewModel.sureCollection(orderNo, "");
        } else {
            urlStrings = "";
            currentImgIndex = 0;
            viewModel.uploadMultiFileModel(this, adapter.getFileList().get(currentImgIndex++));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
    }

}
